//
//  OYUserInfoViewModel.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/3.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit

class OYUserInfoViewModel: NSObject {
    /// 用户信息的单例对象
    static let sharedUserInfo: OYUserInfoViewModel = OYUserInfoViewModel()
    
    /// 用户的登录成功信息
    var userInfo:OYAccessModel?{
        // 通过解档获取用户登录成功的信息
        return OYAccessModel.loadUserAccount()
    }
    
    var isLogin:Bool {
        return accessToken != nil
    }
    
    var accessToken: String?{
        guard let token = userInfo?.access_token else { return nil }
        
        if userInfo?.expireDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return token
        } else {
            return nil
        }
    }
    
    
    // MARK: -通过授权码发送请求获取accesstoken令牌
    func getAccessToken(code:String,callBack:@escaping (Bool)->()) {
        OYNetWorkTools.sharedTools.getAccessToken(code: code, callBack: { (response, error) in
            if error != nil {
                callBack(false)
                print("请求令牌失败")
                return
            }else {
                let dict = response as! [String: Any]
                
                // 字典转为模型
                let accessModel = OYAccessModel(dict: dict)
                
                self.getUserInfo(accessModel: accessModel,callBack: callBack)
                
                
            }
            
        })
    }
    
    // MARK: -通过accesstoken发送请求，获取用户信息
    func getUserInfo(accessModel:OYAccessModel,callBack:@escaping (Bool)->()){
        OYNetWorkTools.sharedTools.getUserInfo(access_token: accessModel.access_token!, uid: accessModel.uid, callBack: { (response,error) in
            if error != nil {
                print("获取用户信息失败")
                print(error)
                callBack(false)
                return
            }else {
                // 运行至此表明获取用户信息成功
                print("获取用户信息成功")
                let dict = response as! [String:Any]
                accessModel.screen_name = dict["screen_name"] as? String
                accessModel.avatar_large = dict["avatar_large"] as? String
                                
                 // MARK: -对数据模型进行归档
                accessModel.saveUserAccount()
                
                callBack(true)
                
            }
            
        })
    }
}
